<?php
declare (strict_types = 1);

namespace app\command;

use app\common\model\Config;
use app\common\self\SelfRedis;
use app\mall\controller\Activity;
use app\mall\model\ActivityLog;
use app\mall\model\GoodsComment;
use app\order\model\Order;
use app\user\model\MiaoLog;
use app\order\model\OrderGoods;
use app\order\model\OrderInfo;
use app\user\model\User;
use app\user\model\UserShareOrder;
use app\user\model\UserWallet;
use app\user\model\WalletOperationLog;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\facade\Log;

class OrderEnd extends Command
{
    public $data;

    protected function configure()
    {
        // 指令配置
        $this->setName('orderend')
            ->setDescription('订单脚本完结');
    }

    protected function execute(Input $input, Output $output)
    {
        // 获取到支付的配置
        $payConfig = Config::where('type','business')->find();
        if(!$payConfig)
            return false;
        $payConfigList =  json_decode($payConfig->content,true);
        // 'receipt', // 待收货  结束 天数
        // 'service' // 售后结束 天数

        // 拿取状态为 待收货3   已收货4  已完成5  没有售后服务
        $time = time();
        $orderModel =  new Order();
        $list = $orderModel->whereIn('status',[3,4])->select();
        $orderModel->startTrans();
        $miaoLogModel = new MiaoLog();
        foreach($list as $item){
            // 如果不等于0  表示在售后 不可结束订单  且不等于售后处理完成的
            if($item->service == 1 || $item->service == 2)
                continue;
            // 待收货 如果大于 后台设置的自动收货时间
            if($item['status'] == 3 && $item->deliver_time &&  $time - $item->deliver_time > $payConfigList['receipt'] * 3600 * 24){
                var_dump('待收货自动确认中....'.'----'.$item->id);
                Log::write([
                    'title' => '-待收货的处理--脚本处理逻辑---',
                    'status' => $item->status,
                    'id' => $item->id
                ],'orderend');
                $item['receive_time'] = $time;$item->status = 4;$item->save();
                $one = $item;
                # 判断是否为 拼团  且 入团
                $orderInfoModel = OrderInfo::where('oid',$one->id)->find();
                if($orderInfoModel && $orderInfoModel->switch_num == 3){
                    $ActivityLogModel = ActivityLog::where('oid',$one->id)->find();
                    # 查找父级 必须有父级id
                    if($ActivityLogModel && $ActivityLogModel->pid > 0 && $ActivityLogPModel = ActivityLog::find($ActivityLogModel->pid)){
                        if($ActivityLogPModel->partake && $listObj = $ActivityLogPModel->partake){
                            $newData = false;
                            # 迭代循环, 需要没有结算 且等于当前
                            foreach($listObj as $k => &$item){
                                if($item['uid'] == $one->uid && $item['status'] == 0){
                                    $item['status']  = 1;
                                    $newData = $item;
                                    $listObj[$k]['status'] = 1;
                                    break;
                                }
                            }
                            if($newData && $newData['miao'] > 0){
                                # 改变状态 并且 修改 状态
                                ActivityLog::where('id',$ActivityLogPModel->id)->update([
                                    'partake' => json_encode($listObj)
                                ]);
                                # 改变 喵呗  并 插入记录   
                                $UserWalletPmodel = UserWallet::where('uid',$ActivityLogPModel->uid)->find();
                                UserWallet::where('uid',$ActivityLogPModel->uid)->update([
                                    'pre_miao' => $UserWalletPmodel->pre_miao -  $newData['miao'] > 0 ? $UserWalletPmodel->pre_miao -  $newData['miao'] : 0,
                                    'miao' => $UserWalletPmodel->miao + $newData['miao'],
                                    'miaos' => $UserWalletPmodel->miaos + $newData['miao']
                                ]);
                                # 记录 钱包操作记录 -  此处需要记录的有三条
                                $wallLogData = [];$time = time();
                                # 记录  -  扣掉 预估喵呗
                                $wallLogData[] = [
                                    'status' => 2,
                                    'type' => 2,
                                    'uid' => $UserWalletPmodel->uid,
                                    'reward' => $newData['miao'],
                                    'extend' => 'ActivityLog',
                                    'extend_id' => $ActivityLogPModel->id,
                                    'describe' => '脚本处理-订单结算-拼团-下级团员处理-扣除待预估喵呗',
                                    'add_time' => $time
                                ];
                                # 记录  -   增加的喵呗
                                $wallLogData[] = [
                                    'status' => 1,
                                    'type' => 2,
                                    'uid' => $UserWalletPmodel->uid,
                                    'reward' => $newData['miao'],
                                    'extend' => 'ActivityLog',
                                    'extend_id' => $ActivityLogPModel->id,
                                    'describe' => '脚本处理-订单结算-拼团-下级团员处理-增加喵呗',
                                    'add_time' => $time
                                ];
                                # 记录  -  -增加累计喵呗
                                $wallLogData[] = [
                                    'status' => 1,
                                    'type' => 2,
                                    'uid' => $UserWalletPmodel->uid,
                                    'reward' => $newData['miao'],
                                    'extend' => 'ActivityLog',
                                    'extend_id' => $ActivityLogPModel->id,
                                    'describe' => '脚本处理-订单结算-拼团-下级团员处理-增加累计喵呗',
                                    'add_time' => $time
                                ];
                                # 喵呗 更改状态 状态为 预估 且 当前订单号 和 父级uid  拼团
                                $miaoLogUId = MiaoLog::where(['status' => 1, 'uid' => $ActivityLogPModel->uid,'oid' => $ActivityLogPModel->oid,'type' => 2,'reward' => $newData['miao']])->update([
                                    'status' => 3 // 入账
                                ]);
                                # 喵呗更改错误
                                #if(!$miaoLogUId) return retu_json(400,'错误');
                                WalletOperationLog::insertAll($wallLogData);
                            }
                        }
                    }
                }
                // 已收货4  已收货 7天后 完结订单 5 且 将喵呗中的记录更新待结算
            }else if($item['status'] == 4  && $item['receive_time'] &&  $time - $item['receive_time'] > $payConfigList['service'] * 3600 * 24){
                var_dump('结算中....'.'----'.$item->id);
                Log::write([
                    'title' => '-已收货的处理--脚本处理逻辑---已完结',
                    'status' => $item->status,
                    'id' => $item->id
                ],'orderend');
                $item['complete_time'] = $time;$item->status = 5;$item->save();
                $orderGoods = OrderGoods::where('order_id',$item->id)->find();
                # 获取喵呗 array  状态为  预估  1
                $miaoLogs = MiaoLog::where(['oid'=>$item->id,'status'=>1])->select();
                if(!$miaoLogs) Log::write('程序bug,请查看，订单id'.$item->id,'订单完成bug-请查看');
                $time = time();
                $sr = new SelfRedis();
                // 钱包
                $wallLogData = [];
                // 迭代
                foreach($miaoLogs as $v){
                    $wallLogData[] = [
                        'status' => 1,
                        'type' => 2,
                        'uid' => $v->uid,
                        'reward' => $v->reward,
                        'extend' => 'order',
                        'extend_id' => $item->id,
                        'describe' => '脚本-订单结算-增加待结算喵呗',
                        'add_time' => $time
                    ];
                    $wallLogData[] = [
                        'status' => 2,
                        'type' => 2,
                        'uid' => $v->uid,
                        'reward' => $v->reward,
                        'extend' => 'order',
                        'extend_id' => $item->id,
                        'describe' => '脚本-订单结算-扣除待结算喵呗',
                        'add_time' => $time
                    ];
                    // 操作钱包
                    $userWall = UserWallet::where('uid',$v->uid)->find();
                    // 扣掉当前喵呗里面的预估 增加待结算的喵呗
                    if($userWall){
                        UserWallet::where('uid',$v->uid)->update([
                            'pre_miao' => $userWall->pre_miao - $v->reward > 0 ? $userWall->pre_miao - $v->reward : 0,
                            'wait_miao' => $userWall->wait_miao + $v->reward
                        ]);
                    }
                }
                # 更改喵呗-记录 待结算状态
                MiaoLog::where('oid',$item->id)->update([
                    'status' => 2, // 改状态为待结算
                ]);
                # 推入 团队
                if($orderGoods->is_team == 1) $b = $sr->redis->set('mmei_miaolog:team:'.$item->id,1,20);
                # 推入 分享
                if($orderGoods->is_sale == 1) $b1 = $sr->redis->set('mmei_miaolog:sale:'.$item->id,1,20);
                # 插入对应的记录 # 插入钱包操作记录
                if($wallLogData)
                    WalletOperationLog::insertAll($wallLogData);
                $miaoLogNum = $miaoLogModel->where('oid',$item->id)->update(['status' => 2]);
                Log::write('喵呗-状态已更新，更新记录如下：'.$miaoLogNum,'orderend');
            }
        }
        $orderModel->commit();
    	$output->writeln('--------模型调用结束---------------');
    }
}
